import sys, time
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import QUrl, pyqtSignal, Qt
from edb.mainwindows import Ui_MainWindow
from edb.mapviewer import MAPVIERWR
from edb.mapdata import MAP
from edb.mapdatabase import MAPDATABASE
from edb.login_windows import LOGIN


class MyWindow(QMainWindow):
    # 登录信号
    login_signal = pyqtSignal(bool)
    def __init__(self, parent=None):
        super().__init__(parent)
        self._init_ui()
        # 无边框
        self._set_none_broder()
        self.database = MAPDATABASE()
        self.map = MAP(self.database, self.ui.outshape, self.ui.showinfo, self.ui.com_shen, self.ui.com_shi)
        self.ms = self.ui.message
        # ================================
        # mapViewer
        self.mapViewer = MAPVIERWR(self)
        # 把mapViewer加入到widget里面
        self.ui.map_viewer.addWidget(self.mapViewer)
        # 初始化选择器
        self.initial_selector()
        # 初始化地图
        self.creat_map()
        # 登录
        LOGIN(self.login_signal, self).exec()
    # 事件重写
    def closeEvent(self, a0) -> None:
        reply = QMessageBox.question(self, '提示', '是否退出', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.database.close()
            a0.accept()
        else:
            a0.ignore()

    def mouseReleaseEvent(self, event):
        # '''鼠标弹起事件'''
        self.mPos = None
        event.accept()

    # 移动功能
    def mousePressEvent(self, event):
        # """鼠标点击事件"""
        if event.button() == Qt.LeftButton:
            self.mPos = event.pos()
        event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton and self.mPos:
            self.move(self.mapToGlobal(event.pos() - self.mPos))
        event.accept()

    def mouseDoubleClickEvent(self, event):
        self.normal_max_switch()
        event.accept()

    def normal_max_switch(self):
        # 切换大小窗口
        if self.isMaximized():
            self.showNormal()
            style = '''.QPushButton{image: url(:/resources/resources/max.png);background:transparent}\
                        .QPushButton:hover{image: url(:/resources/resources/max_hover.png);background:transparent}
                        '''
            self.ui.max.setStyleSheet(style)
        else:
            self.showMaximized()
            style = '''.QPushButton{image: url(:/resources/resources/normal.png);background:transparent}\
                        .QPushButton:hover{image: url(:/resources/resources/normal_hover.png);background:transparent}
                        '''
            self.ui.max.setStyleSheet(style)

    def _init_ui(self):
        # 初始化和ui相关的事件等
        self.mPos = None
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.com_shen.currentIndexChanged.connect(self.check_combox_change)
        # 绑定按钮
        self.ui.flash.clicked.connect(self.creat_map)
        self.login_signal.connect(self.login)
        self.ui.close.clicked.connect(self.close)
        self.ui.min.clicked.connect(self.showMinimized)
        self.ui.max.clicked.connect(self.normal_max_switch)

    def _set_none_broder(self):
        # 无边框
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
        # 添加阴影
        self.setAttribute(Qt.WA_TranslucentBackground)
        # effect = QGraphicsDropShadowEffect(self)
        # effect.setBlurRadius(12)
        # effect.setOffset(0, 0)
        # effect.setColor(Qt.gray)
        # self.setGraphicsEffect(effect)

    # 功能函数
    def creat_map(self):
        self.info('开始创建地图......')
        # 查看选中的金属类型
        types = self.haveymetal_types()
        # 显示map页面 info是格式字符串
        file_path = self.map.get_map(types, self.ui.map.currentText())
        self.mapViewer.load(QUrl.fromLocalFile(file_path))

    def haveymetal_types(self):
        _ = ['Cr总', 'Cu总', 'Pb总', 'Zn总', 'Mn总']
        check_box = [self.ui.cb_Cr.isChecked(),
                     self.ui.cb_Cu.isChecked(),
                     self.ui.cb_Pb.isChecked(),
                     self.ui.cb_Zn.isChecked(),
                     self.ui.cb_Mn.isChecked()
                     ]
        return [y for x, y in enumerate(_) if check_box[x]]


    def initial_selector(self):
        shen_list = self.database.find('DISTINCT 省份')
        for value in shen_list:
            self.ui.com_shen.addItem(value.get('省份'))
        shi_list = self.database.find('DISTINCT 城市')
        for value in shi_list:
            self.ui.com_shi.addItem(value.get('城市'))

    def check_combox_change(self):
        shen = self.ui.com_shen.currentText()
        print('选择器修改为：{}'.format(shen))
        self.info('选择器修改为：{}'.format(shen))
        if shen == '全部':
            # 清空combox
            self.ui.com_shi.clear()
            self.ui.com_shi.addItem('全部')
            # 返回全部城市
            shi_list = self.database.find('DISTINCT 城市')
            for value in shi_list:
                self.ui.com_shi.addItem(value.get('城市'))
        else:
            # 清空combox
            self.ui.com_shi.clear()
            self.ui.com_shi.addItem('全部')
            # != 全部 返回选中的省份的城市
            shi_list = self.database.find('DISTINCT 城市', ' WHERE 省份=\'{}\''.format(shen))
            for value in shi_list:
                self.ui.com_shi.addItem(value.get('城市'))

    def info(self, message: str):
        self.ms.append("[{}]{}".format(time.strftime('%H:%M:%S'), message))

    # 登录功能
    def login(self, flag):
        if flag:
            # 密码正确
            self.show()
        else:
            # 关闭登录窗口,主窗口也关闭
            quit()

# =========================================================================


if __name__ == '__main__':
    # 启动界面，不用修
    app = QApplication(sys.argv)
    myWin = MyWindow()
    # myWin.show()
    # 引导登录界面
    sys.exit(app.exec_())
